controllers.controller('StationsCtrl', ['$rootScope', '$scope', '$http', '$q', function($rootScope,$scope, $http, $q) {
    $http(jsRoutes.controllers.StationsController.getAllStations()).success(function(data, status, headers, config) {
        //sababa
        $scope.stations = data;
    }).error(function(data, status, headers, config) {
            alert("error fetching stations")
        })

    $('#stationTabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    })

    $scope.handleStationSubmit = function(station, action) {
        var defer = $q.defer();
        $http.post(jsRoutes.controllers.StationsController.saveStation().url, station).success(function(data) {
            $scope.station = null;
            $scope.editedStation = null;
            if(action === 'new') {
                $scope.stations.push(data);
            }else if(action === 'update'){
                $scope.stations.forEach(function(d) {
                    if(d.id == station.id){
                        station = d;
                    }
                });
                var index = $scope.stations.indexOf(station);
                $scope.stations[index] = data;
            }
            defer.resolve();
            $rootScope.$$childTail.successMsg.push('Saved successfully!');
        }).error(function() {
                $rootScope.$$childTail.successMsg.push('Error! try again later');
            })

        $scope.submitPromise = defer.promise;
    }

    $scope.deleteStationWithConfirm = function(station) {
        if(station.id){
            $('#confirm')
                .modal({ backdrop: 'static', keyboard: false })
                .one('click', '[data-value]', function (e) {
                    if($(this).data('value')) {
                        $http.post(jsRoutes.controllers.StationsController.deleteStation().url, station).success(function() {
                            console.log("this is success")

                            $scope.editedStation = null;
                            $scope.station = null;
                            $scope.stations.forEach(function(d) {
                                if(d.id == station.id){
                                    station = d;
                                }
                            });
                            var index = $scope.stations.indexOf(station);
                            $scope.stations.splice(index, 1);
                        }).error(function() {
                                console.log("this is error"+arguments)
                            })
                    }
                });

        }
    }

    $scope.stationChanged = function() {
        console.log($scope.station);
        $scope.editedStation = angular.fromJson($scope.station);
        console.log($scope.station);
    }

}]);